import React, { FC, useCallback, useEffect, useState } from 'react';

import { IQueryData, IState } from '../typings';
import { useSelector } from 'react-redux';
import { useCurQuestion } from '../hooks';
import * as H from 'history';

import Header from '../components/Header';
import TestPanel from '../components/TestPanel';

interface IProps {
  history: H.History;
}

enum HEADER_TITLE {
  loading = '试题加载中...',
  testing = '考试中'
}

const Test: FC<IProps> = ({ history }) => {
  //在考题加载的时候显示试题加载中
  //在试题加载完毕的时候显示考试中
  const [headerTitle, setHeaderTitle] = useState<string>(HEADER_TITLE.loading);
  const [curIdx, setCurIdx] = useState<number>(0);
  const total: number = useSelector((state: IState) => state.total);
  //该条数据是稳定存储在当前组件state里
  const queryList: IQueryData[] = useSelector(
    (state: IState) => state.queryList
  );

  //通过自定义Hooks拿到setCurQuestion方法去修改curQuestion数组(该数组保存第一条题目信息)
  const [curQuestion, setCurQuestion] = useCurQuestion();

  //当前题目存在时 设置title为考试中
  useEffect(() => {
    //判断curQuestion里有没有第一条数据
    //存在时向后执行程序
    //更改标题名称
    curQuestion && setHeaderTitle(HEADER_TITLE.testing);
  }, [curQuestion]);

  //当curIdx有变化的时候 设置下一题
  useEffect(() => {
    //设置加载中
    setHeaderTitle(HEADER_TITLE.loading);

    //保存当前题目 curQuestion = 新的[]来源于queryList[curIdx]
    setCurQuestion(queryList[curIdx]);
  }, [queryList, curIdx, setCurQuestion]);

  //点击下一题按钮时 要判断
  const onNextQuestion: () => void = useCallback(() => {
    //跳转下一题
    //0 <= 5-1
    if (curIdx <= total - 1) {
      //更改curIdx + 1
      setCurIdx((curIdx: number) => curIdx + 1);
    } else {
      //超过5 跳转结果页面
      history.push('/result');
    }
  }, [curIdx, total, history]);

  return (
    <div className="container">
      <Header headerTitle={headerTitle} iconShow={true}></Header>
      {/* 平铺需要用到的参数(! 必须要拿到再传入) */}
      <TestPanel {...curQuestion!} onNextQuestion={onNextQuestion} />
    </div>
  );
};

export default Test;
